<template>
  <el-dialog v-model="props.addVisible" title="添加生产任务" width="55%" :before-close="handleClose"
             class="production-task-dialog" append-to-body>
    <el-form :model="props.datas" :rules="rules" ref="formRef" label-width="100px">
      <!-- Workstation -->
      <el-row>
        <el-col :span="8">
          <el-form-item label="工作站" prop="workstationName" required>
            <el-input v-model="props.datas.workstationName" readonly placeholder="请选择工作站" style="width: 180px;">
              <template #append>
                <el-button @click="selectedRank">
                  <el-icon>
                    <Search/>
                  </el-icon>
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="甘特图显示颜色" label-width="180px" prop="color" required>
            <el-color-picker v-model="props.datas.colorCode" class="ml-2"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-input v-model="props.datas.colorCode" readonly placeholder="请选择颜色" style="width: 150px;"/>
        </el-col>
      </el-row>

      <!-- Production Quantity -->
      <el-form-item label="排产数量" prop="quantity" required>
        <el-input-number
            v-model="props.datas.quantity"
            :min="1"
            controls-position="right"
            class="w-32"
        />
      </el-form-item>

      <!-- Start Time -->
      <el-row>
        <el-col :span="8">

          <el-form-item label="开始时间" prop="startTime" required>
            <el-date-picker
                v-model="props.datas.startTime"
                type="datetime"
                placeholder="请选择开始生产时间"
                class="w-full"
                @change="endTimeChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生产时长" prop="duration" required>
            <el-input-number
                v-model="props.datas.duration"
                :min="1"
                class="w-32"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="完成时间">
            <el-date-picker
                v-model="props.datas.endTime"
                disabled
                type="datetime"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          确定
        </el-button>
      </span>
    </template>
    <select-workstation :dialogVisible="dialogVisible" :processCode="props.processCode" @data-return="workData"
                        @close="CloseSelect"/>
  </el-dialog>
</template>

<script setup>
import {ref} from 'vue'
import {Search} from '@element-plus/icons-vue'
import SelectWorkstation from "@/components/ProductionScheduling/SelectWorkstation.vue";
import {ElMessage} from "element-plus";
import {updateTask} from "@/apis/zyj/ProductionSceduling.js";

const props = defineProps({
  addVisible: Boolean,
  processCode: String,
  form: Object,
  procedureCode: String,
  datas: Array
})
const emit = defineEmits(['close'])
const formRef = ref(null)
const dialogVisible = ref(false)

const form = ref({
  workstationName: '',
  quantity: 1,
  startTime: '',
  duration: 1,
  colorCode: '#00AEF3'
})

function createID() {
  let code = 'TASK';
  let date = new Date();
  let year = date.getFullYear();
  code = code + year + Math.floor(Math.random() * 10000);
  return code;
}

const rules = {
  workstationName: [
    {required: true, message: '请选择工作站', trigger: 'blur'}
  ],
  quantity: [
    {required: true, message: '请输入排产数量', trigger: 'blur'}
  ],
  startTime: [
    {required: true, message: '请选择开始时间', trigger: 'blur'}
  ],
  duration: [
    {required: true, message: '请输入生产时长', trigger: 'blur'}
  ]
}

const endTimeChange = (row) => {
  const date = new Date(row)
  date.setHours(date.getHours() + props.datas.duration)

  // 自定义格式化函数
  function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  props.datas.endTime = formatDate(date);
}

// 自定义格式化函数
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const selectedRank = () => {
  dialogVisible.value = true
}

const CloseSelect = () => {
  dialogVisible.value = false
}
const workData = (row) => {
  console.log(row)
  props.datas.workstationName = row.workstationName
  props.datas.workstationCode = row.workstationCode
  props.datas.workstationId = row.workstationId
  props.datas.processCode = row.processCode
  props.datas.processName = row.process.processName

}

const handleClose = (done) => {
  emit('close')
}

const handleSubmit = async () => {
  console.log(props.datas)
  await updateTask(props.datas).then(res => {
    if (res == "成功") {
      ElMessage.success('修改成功!')
      handleClose()
    } else ElMessage.error("修改失败！")
  })
}
</script>

<style scoped>
.production-task-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>